package com.example.zookeeper.lock.util;

import com.example.zookeeper.lock.watch.DefaultWatch;
import org.apache.zookeeper.ZooKeeper;

import javax.management.DescriptorAccess;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Vicente
 * @version 1.0
 * @date 2020/3/9 14:49
 */
public class ZookeeperUtils {
    private static ZooKeeper zooKeeper;
    private static final String url = "47.95.192.77:2181,47.95.192.77:2182,47.95.192.77:2183/testLock";
    private static DefaultWatch defaultWatch = new DefaultWatch();
    private static CountDownLatch latch = new CountDownLatch(1);

    public static ZooKeeper getZooKeeper() {
        try {
            zooKeeper = new ZooKeeper(url,1000,defaultWatch);
            defaultWatch.setZooKeeper(zooKeeper);
            defaultWatch.setLatch(latch);
            latch.await();          //阻塞，zookeeper对象连接成功再返回
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }
}
